import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../app_services.dart';

/// 现代化服务使用示例
/// 
/// 这个示例展示了如何使用新的服务架构：
/// 1. 使用Riverpod进行状态管理
/// 2. 使用Repository模式处理数据
/// 3. 使用函数式编程处理错误
/// 4. 简洁的API调用

class ModernServiceExample extends ConsumerWidget {
  const ModernServiceExample({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      appBar: AppBar(title: const Text('现代化服务示例')),
      body: const SingleChildScrollView(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            _AuthSection(),
            SizedBox(height: 32),
            _TunnelSection(),
          ],
        ),
      ),
    );
  }
}

/// 认证部分示例
class _AuthSection extends ConsumerWidget {
  const _AuthSection();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final authState = ref.watch(authProvider);
    final authNotifier = ref.read(authProvider.notifier);

    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const Text('认证功能', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            const SizedBox(height: 16),
            
            if (authState.isAuthenticated) ...[
              Text('欢迎, ${authState.user?.username}!'),
              const SizedBox(height: 8),
              Text('手机号: ${authState.user?.phoneNumber}'),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: authState.isLoading ? null : () => authNotifier.logout(),
                child: authState.isLoading 
                  ? const CircularProgressIndicator()
                  : const Text('登出'),
              ),
            ] else ...[
              const Text('未登录'),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: authState.isLoading ? null : () => _showLoginDialog(context, authNotifier),
                child: authState.isLoading 
                  ? const CircularProgressIndicator()
                  : const Text('登录'),
              ),
            ],
            
            if (authState.error != null) ...[
              const SizedBox(height: 8),
              Text(
                '错误: ${authState.error}',
                style: const TextStyle(color: Colors.red),
              ),
              TextButton(
                onPressed: () => authNotifier.clearError(),
                child: const Text('清除错误'),
              ),
            ],
          ],
        ),
      ),
    );
  }

  void _showLoginDialog(BuildContext context, AuthNotifier authNotifier) {
    final phoneController = TextEditingController();
    final codeController = TextEditingController();
    String? verificationId;

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('登录'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: phoneController,
              decoration: const InputDecoration(labelText: '手机号'),
              keyboardType: TextInputType.phone,
            ),
            const SizedBox(height: 8),
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: codeController,
                    decoration: const InputDecoration(labelText: '验证码'),
                    keyboardType: TextInputType.number,
                  ),
                ),
                TextButton(
                  onPressed: () async {
                    if (phoneController.text.isNotEmpty) {
                      await authNotifier.sendVerificationCode(phoneController.text);
                      // 这里应该从状态中获取verificationId
                      verificationId = 'mock_verification_id';
                    }
                  },
                  child: const Text('发送验证码'),
                ),
              ],
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              if (phoneController.text.isNotEmpty && 
                  codeController.text.isNotEmpty &&
                  verificationId != null) {
                authNotifier.verifyCodeAndLogin(
                  phoneNumber: phoneController.text,
                  code: codeController.text,
                  verificationId: verificationId!,
                );
                Navigator.of(context).pop();
              }
            },
            child: const Text('登录'),
          ),
        ],
      ),
    );
  }
}

/// 隧道部分示例
class _TunnelSection extends ConsumerWidget {
  const _TunnelSection();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final tunnelState = ref.watch(tunnelProvider);
    final tunnelNotifier = ref.read(tunnelProvider.notifier);
    final isAuthenticated = ref.watch(isAuthenticatedProvider);

    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text('隧道管理', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                IconButton(
                  onPressed: isAuthenticated && !tunnelState.isLoading 
                    ? () => tunnelNotifier.fetchTunnels()
                    : null,
                  icon: const Icon(Icons.refresh),
                ),
              ],
            ),
            const SizedBox(height: 16),

            if (!isAuthenticated) ...[
              const Text('请先登录以查看隧道'),
            ] else if (tunnelState.isLoading) ...[
              const Center(child: CircularProgressIndicator()),
            ] else if (tunnelState.tunnels.isEmpty) ...[
              const Text('暂无隧道'),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: () => _showCreateTunnelDialog(context, tunnelNotifier),
                child: const Text('创建隧道'),
              ),
            ] else ...[
              ...tunnelState.tunnels.map((tunnel) => _TunnelItem(tunnel: tunnel)),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: () => _showCreateTunnelDialog(context, tunnelNotifier),
                child: const Text('创建新隧道'),
              ),
            ],

            if (tunnelState.error != null) ...[
              const SizedBox(height: 8),
              Text(
                '错误: ${tunnelState.error}',
                style: const TextStyle(color: Colors.red),
              ),
              TextButton(
                onPressed: () => tunnelNotifier.clearError(),
                child: const Text('清除错误'),
              ),
            ],
          ],
        ),
      ),
    );
  }

  void _showCreateTunnelDialog(BuildContext context, TunnelNotifier tunnelNotifier) {
    final localHostController = TextEditingController(text: 'localhost');
    final localPortController = TextEditingController();
    final serverNameController = TextEditingController();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('创建隧道'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: localHostController,
              decoration: const InputDecoration(labelText: '本地主机'),
            ),
            TextField(
              controller: localPortController,
              decoration: const InputDecoration(labelText: '本地端口'),
              keyboardType: TextInputType.number,
            ),
            TextField(
              controller: serverNameController,
              decoration: const InputDecoration(labelText: '服务名称'),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              if (localHostController.text.isNotEmpty && 
                  localPortController.text.isNotEmpty &&
                  serverNameController.text.isNotEmpty) {
                tunnelNotifier.createTunnel(
                  localHost: localHostController.text,
                  localPort: localPortController.text,
                  serverName: serverNameController.text,
                );
                Navigator.of(context).pop();
              }
            },
            child: const Text('创建'),
          ),
        ],
      ),
    );
  }
}

/// 隧道项目组件
class _TunnelItem extends ConsumerWidget {
  const _TunnelItem({required this.tunnel});

  final TunnelData tunnel;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final connectionState = ref.watch(tunnelConnectionStateProvider(tunnel.tunnelId));
    final tunnelNotifier = ref.read(tunnelProvider.notifier);

    return Card(
      margin: const EdgeInsets.symmetric(vertical: 4),
      child: ListTile(
        leading: Icon(
          _getStatusIcon(connectionState?.status),
          color: _getStatusColor(connectionState?.status),
        ),
        title: Text(tunnel.serverName),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('${tunnel.localHost}:${tunnel.localPort}'),
            SelectableText('公网地址: ${tunnel.publicAddress}'),
            if (connectionState?.status != null)
              Text('状态: ${_getStatusText(connectionState!.status)}'),
          ],
        ),
        trailing: IconButton(
          onPressed: () => tunnelNotifier.deleteTunnel(tunnel.tunnelId),
          icon: const Icon(Icons.delete, color: Colors.red),
        ),
        onTap: () {
          // 这里可以添加连接/断开逻辑
        },
      ),
    );
  }

  IconData _getStatusIcon(TunnelConnectionStatus? status) {
    switch (status) {
      case TunnelConnectionStatus.connected:
        return Icons.check_circle;
      case TunnelConnectionStatus.connecting:
        return Icons.hourglass_empty;
      case TunnelConnectionStatus.error:
        return Icons.error;
      case TunnelConnectionStatus.disconnected:
      case null:
        return Icons.radio_button_unchecked;
    }
  }

  Color _getStatusColor(TunnelConnectionStatus? status) {
    switch (status) {
      case TunnelConnectionStatus.connected:
        return Colors.green;
      case TunnelConnectionStatus.connecting:
        return Colors.orange;
      case TunnelConnectionStatus.error:
        return Colors.red;
      case TunnelConnectionStatus.disconnected:
      case null:
        return Colors.grey;
    }
  }

  String _getStatusText(TunnelConnectionStatus status) {
    switch (status) {
      case TunnelConnectionStatus.connected:
        return '已连接';
      case TunnelConnectionStatus.connecting:
        return '连接中';
      case TunnelConnectionStatus.error:
        return '错误';
      case TunnelConnectionStatus.disconnected:
        return '已断开';
    }
  }
}

